<?php

namespace App\Http\Controllers;

use App\Models\Bill;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\DB;
use App\Models\Balance;

class BillController extends Controller
{
    // 获取分页账单列表（已受JWT保护）
    public function index()
    {
        return auth()->user()->bills()
            ->with('billType:id,name,icon') // 仅加载必要字段
            ->paginate(10);
    }

    // 添加新方法
    public function byMonth(Request $request)
    {
        $validated = $request->validate([
            'year' => 'nullable|integer|digits:4|min:2000',
            'month' => 'nullable|integer|between:1,12',
            'date' => 'nullable|integer|between:1,31'
        ]);
        $year = $validated['year'] ?? null;
        $month = $validated['month'] ?? null;
        $date = $validated['date'] ?? null;
        if  ($year &&$month &&$date ) {
            $query = auth()->user()->bills()
            ->with('billType:id,name,icon,flow')
            ->whereYear('bill_time', $year)
            ->whereMonth('bill_time', $month)
            ->whereDay('bill_time', $date);
        }elseif ($year  &&$month ) {
            $query = auth()->user()->bills()
            ->with('billType:id,name,icon,flow')
            ->whereYear('bill_time', $year)
            ->whereMonth('bill_time', $month);
        }elseif ($year ) {
            $query = auth()->user()->bills()
            ->with('billType:id,name,icon,flow')
            ->whereYear('bill_time', $year);
        }else{
            $query = auth()->user()->bills()
            ->with('billType:id,name,icon,flow');
        }
        

        return response()->json([
            'data' => $query->paginate(
                $request->get('per_page', 15) // 允许自定义分页数量
            )
        ]);
    }

    // 获取全部账单（不分页）
    public function getAll(Request $request)
{
    $validated = $request->validate([
        'year' => 'nullable|integer|digits:4|min:2000',
        'month' => 'nullable|integer|between:1,12',
        'day' => 'nullable|integer|between:1,31',
        'start_date' => 'nullable|date',
        'end_date' => 'nullable|date|after_or_equal:start_date'
    ]);

    $query = auth()->user()->bills()
        ->with('billType:id,name,flow')
        ->select('id', 'bill_type_id', 'amount', 'bill_time', 'remark')
        ->orderBy('bill_time', 'desc');

    // 年月日筛选
    if ($validated['year'] ?? false) {
        $query->whereYear('bill_time', $validated['year']);
    }
    if ($validated['month'] ?? false) {
        $query->whereMonth('bill_time', $validated['month']);
    }
    if ($validated['day'] ?? false) {
        $query->whereDay('bill_time', $validated['day']);
    }
    
    // 日期范围筛选
    if ($validated['start_date'] ?? false) {
        $query->whereDate('bill_time', '>=', $validated['start_date']);
    }
    if ($validated['end_date'] ?? false) {
        $query->whereDate('bill_time', '<=', $validated['end_date']);
    }

    return response()->json([
        'data' => $query->get(),
        'count' => $query->count() // 返回总记录数
    ]);
}

    // 创建账单（已包含JWT用户绑定）
    public function store(Request $request)
    {
        $validated = $request->validate([
            'bill_type_id' => 'required|exists:bill_types,id',
            'amount' => 'required|numeric',
            'bill_time' => 'required|date',
            'remark' => 'nullable|string|max:255'
        ]);

        $bill = auth()->user()->bills()->create($validated);

        // 加载账单类型流向
    $bill->load('billType:id,flow');
    $flowType = $bill->billType->flow; // 'income' 或 'expense'
    
     // 加载账单类型流向
     $bill->load('billType:id,flow');
     $flowType = $bill->billType->flow; // 'income' 或 'expense'
     
     // 修复余额更新逻辑
     DB::transaction(function () use ($flowType, $bill) {
         $user = auth()->user();
         
         // 获取或创建余额记录（返回模型实例）
         $balance = Balance::firstOrCreate(
             ['user_id' => $user->id],
             ['balance' => 0]
         );
         
         // 锁定记录防止并发
         $lockedBalance = Balance::where('id', $balance->id)
                               ->lockForUpdate()
                               ->first();
         
         if ($flowType === 'income') {
             $lockedBalance->balance += $bill->amount;
         } else { // expense
             $newBalance = $lockedBalance->balance - $bill->amount;
             if ($newBalance < 0) {
                 throw new \Exception('用户余额不足');
             }
             $lockedBalance->balance = $newBalance;
         }
         
         $lockedBalance->save();
     });


        return response()->json([
            'data' => $bill->load('billType:id,name'),
            'message' => '账单创建成功'
        ], Response::HTTP_CREATED);
    }

    // 查看单个账单（增加权限验证）
    public function show(Bill $bill)
    {
        $this->authorize('view', $bill);

        return response()->json([
            'data' => $bill->load('billType:id,name')
        ]);
    }

    // 更新账单（全验证流程）
    public function update(Request $request, Bill $bill)
    {
        $this->authorize('update', $bill);

        $validated = $request->validate([
            'bill_type_id' => 'sometimes|exists:bill_types,id',
            'amount' => 'sometimes|numeric|min:0.01|max:1000000'
        ]);

        $bill->update($validated);

        return response()->json([
            'data' => $bill->fresh('billType:id,name'),
            'message' => '账单更新成功'
        ]);
    }

    // 删除账单（安全验证）
    public function destroy(Bill $bill)
    {
        $this->authorize('delete', $bill);

        $bill->delete();

        return response()->json([
            'message' => '账单已删除'
        ], Response::HTTP_NO_CONTENT);
    }
}
